package com.qf.flashlib.http.converter;

import com.google.gson.Gson;
import com.qf.flashlib.base.BaseResponse;
import com.qf.flashlib.exception.ServerException;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    /**
     * 针对数据返回成功、错误不同类型字段处理
     */
    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            // 这里的type实际类型是 BaseResponse<PhoneBean>  PhoneBean就是retData要获取的对象。
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            int code = result.getCode();
            if (code == 0) {
                return gson.fromJson(response, type);
            } else {
                BaseResponse errResponse = gson.fromJson(response, BaseResponse.class);
                throw new ServerException(code, errResponse.getMsg());
            }
        } finally {
            value.close();
        }
    }
}